<template>
  <div class="activity-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>活动管理</span>
        </div>
      </template>
      <div class="content-body">
        <!-- 搜索和筛选区域 -->
        <div class="search-filter">
          <el-input 
            v-model="queryForm.title" 
            placeholder="请输入活动标题搜索"
            style="width: 200px; margin-right: 10px;"
            prefix-icon="Search"
            clearable
          />
          <el-select 
            v-model="queryForm.status" 
            placeholder="请选择状态"
            style="width: 120px; margin-right: 10px;"
          >
            <el-option label="全部" value="" />
            <el-option label="生效中" value="1" />
            <el-option label="已下架" value="0" />
          </el-select>
          <el-button type="primary" @click="getList">搜索</el-button>
          <el-button type="primary" @click="handleAddActivity">新增活动</el-button>
        </div>
        
        <!-- 活动列表 -->
        <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
          <el-table-column prop="id" label="活动ID" width="80" />
          <el-table-column prop="title" label="活动标题" min-width="200" :show-overflow-tooltip="true" />
          <el-table-column prop="address" label="活动地址" min-width="200" :show-overflow-tooltip="true" />
          <el-table-column prop="activityTime" label="活动时间" width="180" />
          <el-table-column prop="totalNum" label="可参加人数" width="100" />
          <el-table-column prop="status" label="状态" width="100" >
            <template #default="scope">
              <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
                {{ scope.row.status === '1' ? '生效中' : '已下架' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="是否启用" width="120" >
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="handleEditActivity(scope.row)">编辑</el-button>
              <el-button 
                type="danger" 
                size="small" 
                @click="handleDeleteActivity(scope.row.id)"
                v-if="!isDeleting"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination 
            v-model:current-page="queryForm.pageNum"
            v-model:page-size="queryForm.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 新增/编辑活动弹窗 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="600px"
    >
      <el-form 
        ref="activityFormRef" 
        :model="activityForm" 
        :rules="formRules"
        label-width="100px"
        style="margin-top: 20px;"
      >
        <el-form-item label="活动标题" prop="title">
          <el-input v-model="activityForm.title" placeholder="请输入活动标题" />
        </el-form-item>
        <el-form-item label="活动地址" prop="address">
          <el-input v-model="activityForm.address" placeholder="请输入活动地址" />
        </el-form-item>
        <el-form-item label="活动时间" prop="activityTime">
          <el-date-picker
            v-model="activityForm.activityTime"
            type="datetime"
            placeholder="选择活动时间"
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="可参加人数" prop="totalNum">
          <el-input-number
            v-model="activityForm.totalNum"
            :min="1"
            :max="1000"
            placeholder="请输入可参加人数"
          />
        </el-form-item>
        <el-form-item label="活动内容" prop="content">
          <el-input
            v-model="activityForm.content"
            type="textarea"
            :rows="5"
            placeholder="请输入活动内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, nextTick, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getActivityList, getActivityDetail, addOrUpdateActivity, deleteActivity, updateActivityStatus } from '@/request/activity.js'

// 搜索表单
const queryForm = ref({
  pageNum: 1,
  pageSize: 10,
  title: '',
  status: ''
})

// 删除状态标记
const isDeleting = ref(false)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增活动')
const activityFormRef = ref(null)
const editingActivityId = ref(null)
const tableData = ref([])
const total = ref(0)

// 活动表单
const activityForm = reactive({
  title: '',
  address: '',
  activityTime: '',
  content: '',
  totalNum: 0,
  status: '1' // 默认生效状态
})

// 表单验证规则
const formRules = {
  title: [
    { required: true, message: '请输入活动标题', trigger: 'blur' },
    { min: 2, max: 100, message: '活动标题长度应在 2 到 100 个字符之间', trigger: 'blur' }
  ],
  address: [
    { required: true, message: '请输入活动地址', trigger: 'blur' },
    { min: 5, max: 200, message: '活动地址长度应在 5 到 200 个字符之间', trigger: 'blur' }
  ],
  activityTime: [
    { required: true, message: '请选择活动时间', trigger: 'change' }
  ],
  totalNum: [
    { required: true, message: '请输入可参加人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '可参加人数至少为1', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入活动内容', trigger: 'blur' },
    { min: 10, message: '活动内容不能少于 10 个字符', trigger: 'blur' }
  ]
}

// 获取活动列表
const getList = () => {
  getActivityList(queryForm.value).then(res => {
    tableData.value = res.records || res
    total.value = res.total || res.length
  }).catch(error => {
    console.error('获取活动列表失败:', error)
    ElMessage.error('获取活动列表失败')
  })
}

// 初始化时获取列表数据
onMounted(() => {
  getList()
})

// 重置表单
const resetForm = () => {
  if (activityFormRef.value) {
    activityFormRef.value.resetFields()
  }
  editingActivityId.value = null
  Object.keys(activityForm).forEach(key => {
    activityForm[key] = key === 'status' ? '1' : ''
  })
}

// 新增活动
const handleAddActivity = () => {
  resetForm()
  dialogTitle.value = '新增活动'
  dialogVisible.value = true
}

// 编辑活动
const handleEditActivity = (activity) => {
  dialogTitle.value = '编辑活动'
  editingActivityId.value = activity.id
  getActivityDetail(activity.id).then(res => {
    // 复制活动数据到表单
    Object.keys(activityForm).forEach(key => {
      activityForm[key] = res[key]
    })
    dialogVisible.value = true
  }).catch(error => {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  })
}

// 提交表单
const handleSubmit = () => {
  activityFormRef.value.validate((valid) => {
    if (valid) {
      // 创建提交表单数据的副本
      const submitData = { ...activityForm }
      
      if (editingActivityId.value) {
        // 编辑模式
        submitData.id = editingActivityId.value
        addOrUpdateActivity(submitData).then(res => {
          ElMessage.success('活动更新成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('活动更新失败')
        })
      } else {
        // 新增模式
        addOrUpdateActivity(submitData).then(res => {
          ElMessage.success('活动添加成功')
          dialogVisible.value = false
          resetForm()
          getList()
        }).catch(() => {
          ElMessage.error('活动添加失败')
        })
      }
    }
  })
}

// 删除活动
const handleDeleteActivity = (id) => {
  ElMessageBox.confirm('确定要删除这个活动吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    isDeleting.value = true
    deleteActivity(id).then(res => {
      ElMessage.success('活动删除成功')
      isDeleting.value = false
      getList()
    }).catch(() => {
      ElMessage.error('活动删除失败')
      isDeleting.value = false
    })
  }).catch(() => {
    isDeleting.value = false
  })
}

// 分页处理
const handleSizeChange = (size) => {
  queryForm.value.pageSize = size
  getList()
}

const handleCurrentChange = (current) => {
  queryForm.value.pageNum = current
  getList()
}

// 更新活动状态
const handleStatusChange = (row) => {
  let msg = row.status === '1' ? '上架' : '下架'
  ElMessageBox.confirm('确定要' + msg + '这个活动吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    updateActivityStatus(row.id, row.status === '1' ? '1' : '0').then(res => {
      ElMessage.success('活动状态更新成功')
      getList()
    }).catch(() => {
      ElMessage.error('活动状态更新失败')
      getList() // 刷新列表以恢复原始状态
    })
  }).catch(() => {
    getList() // 刷新列表以恢复原始状态
  })
}
</script>

<style scoped>
.activity-management {
  padding: 0px;
}

.search-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>